<?php

namespace App\Code\Controllers;

use App\Code\Repositories\CmType;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use App\Models\CmSubject;
use Illuminate\Http\Request;
use Dcat\Admin\Http\Controllers\AdminController;

class CmTypeController extends AdminController
{
    public function selectCmType(Request $request)
    {
        $q = $request->get('q');
        return CmSubject::where('subject_name', 'like', "%$q%")->paginate(null, ['id', 'subject_name as text']);
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
//        $list = \App\Models\CmType::query()->with('subject')->get()->toArray();
//        dd($list);
        return Grid::make(new CmType(['subject']), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('type_name');
            // 关联课程
            $grid->column('subject.subject_name', '编程科目名称');
            $grid->column('img_url', 'logo')->width('10px')->image();
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();
            $grid->disableViewButton();
            $grid->filter(function (Grid\Filter $filter) {
                // 更改为 panel 布局
                $filter->panel();
                $filter->like('type_name');
                // 编程科目名称
                $filter->where('subject_name', function ($query) {
                    $query->whereHas('subject', function ($query) {
                        $query->where('subject_name', 'like', "%{$this->input}%");
                    });
                }, '编程科目名称');
            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new CmType(['subject']), function (Show $show) {
            $show->field('id');
            $show->field('type_name');
            // 展示课程
            $show->field('subject.subject_name', '编程科目名称');
            $show->field('desc');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new CmType(), function (Form $form) {
            $form->display('id');
            $form->text('type_name');
            //设置下拉框
            $form->select('s_id', '科目id')->options(function ($id) {
                $subject = CmSubject::find($id);

                if ($subject) {
                    return [$subject->id => $subject->subject_name];
                }
            })->ajax('api/cm_type');
            $form->text('desc');
            $form->image('img_url')->uniqueName()->autoUpload();
            $form->display('created_at');
            $form->display('updated_at');
        });
    }
}
